window.onload = function() {
    window.publish = function(e) {
        var event = e || window.event;
        var $v = $(e.target).closest('.preview-markdown-frame').find('.markdown-preview');
        
        $v = $v.clone();
        $v.find('img').each(function(_i, img) {
            var $img = $(img);
            var nw = img.naturalWidth || 0,
                nh = img.naturalHeight || 0,
                cw = img.clientWidth || 0,
                ch = img.clientHeight || 0,
                jw = $img.width(),
                jh = $img.height();
            var w = Math.max(nw, cw, jw),
                h = Math.max(nh, ch, jh);
            $img.attr({
                'data-width': w,
                'data-height': h,
                'data-src': $img.attr('src')
            });
            $img.attr('src', '');
        });
        
        var c = $v.html();
            $h = $v.find('h1:eq(0)');
        var h = null;
        if($h.length > 0) {
            h = $h.text().trim();
        }
        var $t = $('.edit-tab .tabs .tab.this');
        var n = $t.attr('data-name');
        var data = {
            name: n,
            content: c,
            title: h
        };
        // console.log(data);
        Tips.loading('发布中', 0);
        $.ajax({
            url: '/kod/gsw-append/publish.php',
            type: 'POST',
            dataType: 'json',
            data: data,
            success: function(data) {
                Tips.close(null, 0);
                console.log(data);
                Tips.tips('发布成功', true);
            },
            error: function(data) {
                console.log(data);
                Tips.tips('发布失败', false);
            }
        });
    };
    setInterval(function() {
        var $pmf = $('.preview-markdown-frame');
        if ($pmf.length > 0) {
            console.log('markdown');
            $pmf.each(function(i, item) {
                var $c = $(item).find('.box').find('.content');
                if($c.length > 0) {
                    // console.log($c);
                    var a_save = [
                        '<a href="javascript:;" class="gsw945-save" onclick="window.publish(window.event)"; title="发布">',
                            '<i class="font-icon icon-save"></i>',
                        '</a>'
                    ].join('');
                    if($c.find('.gsw945-save').length < 1) {
                        $c.prepend(a_save);
                    }
                }
            });
        } else {
            console.log('normal');
        }
    }, 3000);
};